// 未完成 忘了抄的书上哪一章了
package main

import (
	"errors"
	"fmt"
	"os"
	"os/signal"
	"time"
)

type Runner struct {
	tasks     []func(int)
	interrupt chan os.Signal
	timeout   <-chan time.Time
	complete  chan error
}

var (
	ErrTimeout   = errors.New("timeout")
	ErrInterrupt = errors.New("interrupt")
)

func (r *Runner) Add(tasks ...func(int)) {
	r.tasks = append(r.tasks, tasks...)
}

func New(d time.Duration) *Runner {
	return &Runner{
		interrupt: make(chan os.Signal, 1),
		timeout:   time.After(d),
		complete:  make(chan error),
	}
}

func (r *Runner) run() error {
	for id, task := range r.tasks {
		if r.getInterrupt() {
			return ErrInterrupt
		}
		task(id)
	}
	return nil
}

func (r *Runner) getInterrupt() bool {
	return true
}

func (r *Runner) Start() error {
	signal.Notify(r.interrupt, os.Interrupt)

	go func() {
		r.complete <- r.run()
	}()
	select {
	case <-r.timeout:
		return ErrTimeout
	}
}
func main() {
	r := New(3 * time.Second)
	r.Add(createTask(), createTask(), createTask())
	_ = r.Start()
}
func createTask() func(int) {
	return func(id int) {
		fmt.Printf("Process task id is %d", id)
		time.Sleep(3 * time.Second)
	}
}
